package com.huiminpay.merchant.common.intercept;

import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.domain.ErrorCode;
import com.huiminpay.common.cache.domain.RestErrorResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse processException(HttpServletRequest req,
                                              HttpServletResponse response,
                                              Exception exception) {
        RestErrorResponse restErrorResponse = new RestErrorResponse();
        if (exception instanceof BusinessException) {
            BusinessException businessException = (BusinessException) exception;
            ErrorCode errorCode = businessException.getErrorCode();
            restErrorResponse.setErrCode(errorCode.getCode());
            restErrorResponse.setErrMessage(errorCode.getDesc());
        } else {
            CommonErrorCode errorCode = CommonErrorCode.UNKNOWN;
            restErrorResponse.setErrCode(errorCode.getCode());
            restErrorResponse.setErrMessage(errorCode.getDesc());
            log.error("异常如下:{}", exception);
        }
        return restErrorResponse;
    }
}
